const express = require('express');
// 引入方法模块
const methods = require('./methods');

const router = express.Router();

//获取json数据
var data = require('./data.json');

// 首页
router.get('/', (req, res) => {
  // 渲染首页
  methods.find((err,book) => {
    if(err){
      console.log('查询失败');
    } 
    res.render('index.html',{list:book})
  })
});

// 添加页面
router.get('/add', (req, res) => {
  res.render('add.html');
});
router.post('/add', (req, res) => {
  let body = req.body;
  new methods(body).save((err) => {
    if(err){
      return status(500).send('Server err');
    }
    res.redirect('/')
  })
});

// 修改页面
router.get('/edit', (req, res) => {
  methods.findById(req.query.id.replace(/"/g,''),(err,book) => {
    res.render('edit.html', {
      arr: book,
    });
  })
});
router.post('/edit', (req, res) => {
  var body = req.body;
  methods.findByIdAndUpdate(body.id,body,(err) => {
    if(err){
      return status(500).send('Server err')
    }
    console.log(body);
    res.redirect('/')
  })
  // console.log(body.id);
});

// 删除页面
router.get('/delete', (req, res) => {
  var id = req.query.id.replace(/"/g,'')
  methods.findByIdAndRemove(id,(err) => {
    if(err){
      // status(500).send('Server err')
      console.log('cuowu');
    }
    res.redirect('/');
  })
});
module.exports = router;
